package com.marcnuri.MAndFileBrowser;

import mydebug.MyDebug;


import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;

public abstract class FileWorker {
	private FileActionDialog progressDialog;
	private Thread workerThread;
	private Runnable workerRunnable;
	private Exception workerException;
	private Handler futureTaskHandler;
	private Runnable futureTaskRunnable;
	public boolean actionCancelled;

	public FileWorker(FileActionDialog progressDialog) {
 this.progressDialog = progressDialog;
 progressDialog.setCancelable(false);
 progressDialog.buttonCancel.setOnClickListener(new OnClickListener() {
 public void onClick(View v) {
 cancel();
 }
 }
 );
 progressDialog.progressPartial.setIndeterminate(false);
 progressDialog.progressAbsolute.setIndeterminate(false);
 actionCancelled = false;
 workerException = null;
 futureTaskHandler = new Handler();
 workerRunnable = new Runnable() {
 public void run() {
 try {
 doInBackGround();
 }
 catch (Exception e) {
 FileWorker.this.workerException = e;
 }
 futureTaskHandler.post(futureTaskRunnable);
 }
 }
;
 workerThread = new Thread(workerRunnable);
 futureTaskRunnable = new Runnable() {
 public void run() {
 done(FileWorker.this.workerException);
 FileWorker.this.progressDialog.dismiss();
 }
 }
;
 }


	public void execute() {
MyDebug.beginMethod("execute:void FileWorker");
 workerThread.start();
 progressDialog.show();
 MyDebug.endMethod();
 }


	protected abstract void doInBackGround() throws Exception;

	protected abstract void done(Exception exception);

	public void publish(final String partialMessage, final Integer partialProgress,
			final Integer partialMax, final String absoluteMessage,
			final Integer absoluteProgress, final Integer absoluteMax) {
MyDebug.beginMethod("publish:void FileWorker");
 futureTaskHandler.post(new Runnable() {
 public void run() {
 process(partialMessage, partialProgress, partialMax, absoluteMessage, absoluteProgress, absoluteMax);
 }
 }
 );
 MyDebug.endMethod();
 }


	private void cancel() {
MyDebug.beginMethod("cancel:void FileWorker");
 actionCancelled = true;
 MyDebug.endMethod();
 }


	private void process(String partialMessage, Integer partialProgress,
			Integer partialMax, String absoluteMessage,
			Integer absoluteProgress, Integer absoluteMax) {
MyDebug.beginMethod("process:void FileWorker");
 if (partialMessage != null) {
 progressDialog.textPartial.setText(partialMessage);
 }
 if (partialProgress != null) {
 progressDialog.progressPartial.setProgress(partialProgress.intValue());
 }
 if (partialMax != null) {
 progressDialog.progressPartial.setMax(partialMax.intValue());
 }
 if (absoluteMessage != null) {
 progressDialog.textAbsolute.setText(absoluteMessage);
 }
 if (absoluteProgress != null) {
 progressDialog.progressAbsolute.setProgress(absoluteProgress.intValue());
 }
 if (absoluteMax != null) {
 progressDialog.progressAbsolute.setMax(absoluteMax.intValue());
 }
 MyDebug.endMethod();
 }

}
